{{ template "layout/header" .}}
{{/*<script src="//cdn.ckeditor.com/4.12.1/full/ckeditor.js"></script>*/}}
<script src="/static/ckeditor/ckeditor.js"></script>
<main id="body">
    <div class="container">
        <div class="row">
            <div class="col-lg-10 mx-auto">
                <div class="card">
                    <div class="card-header">
                        回复详情
                    </div>
                    <div class="card-body">
                        <form action="/api/v1/post/{{.post.ID}}/update" method="post" id="advance_reply_form" class="d-block">
                            <input type="hidden" id="quotetid" name="post_id" value="{{.post.ID}}">
                            <input type="hidden" id="docutype" name="docutype" value="0">
                            {{/*<div class="message mt-1">
                                <textarea class="form-control" id="editor1" placeholder="内容" name="message"></textarea>
                            </div>*/}}
                            <div class="form-group">
                                <textarea class="form-control" id="editor1" placeholder="内容" name="message">
                                    {{.post.Message}}
                                </textarea>
                            </div>
                            <div class="form-group">
                                <input type="text" class="form-control" placeholder="编辑原因" name="update_reason" value="" maxlength="128">
                            </div>
                            <div class="text-muted mt-2 small">
                                <div class="d-flex justify-content-between">
                                    <div class="attachlist_parent">
                                        <a class="small text-left" href="javascript:void(0)">
                                            <label class="addattach" id="addattach">
                                                <i class="icon-folder-open-o"></i>
                                                添加附件
                                                <input type="file" id="add_attach" multiple="multiple" class="invisible">
                                            </label>
                                        </a>
                                        {{if .attachs}}
                                            <fieldset class="fieldset">
                                                <legend>上传的附件：</legend>
                                                <ul class="attachlist">
                                                    {{range .attachs}}
                                                        <li aid="{{.ID}}">
                                                            <a href="/{{.Filename}}" target="_blank">
                                                                <i class="icon filetype {{.Filetype}}"></i>
                                                                {{.Orgfilename}}
                                                            </a>
                                                            <a onclick="deleteAttach(this, {{.PostID}}, {{.ID}})" href="javascript:void(0)" class="delete ml-3"><i class="icon-remove"></i> 删除</a>
                                                        </li>
                                                    {{end}}
                                                </ul>
                                            </fieldset>
                                        {{end}}
                                    </div>
                                    <div>
                                        <button id="postsubmit" type="button" class="btn btn-sm btn-secondary" id="submit" data-loading-text="正在提交..."> 确认修改 </button>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
            <a role="button" class="btn btn-secondary btn-block xn-back col-lg-6 mx-auto mb-3" href="javascript:history.back();">返回</a>
        </div>
    </div>
</main>
<script>


    CKEDITOR.replace('message', {
        language: 'zh-cn',
        disallowedContent: '<script >',
        // toolbar: [['Smiley']],
        // toolbarCanCollapse: true,
        toolbarStartupExpanded: false,
        toolbar: [
            { name: 'document', items: [ 'Source', '-', 'Preview' ] },
            { name: 'clipboard', items: [ 'Cut', 'Copy', 'Paste', 'PasteText', '-', 'Undo', 'Redo' ] },
            { name: 'basicstyles', items: [ 'Bold', 'Italic', 'Underline', 'RemoveFormat' ] },
            { name: 'colors', items: [ 'TextColor'] },
            { name: 'paragraph', items: [ 'NumberedList', 'BulletedList', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-' ] },
            { name: 'links', items: [ 'Link', 'Unlink' ] },
            { name: 'insert', items: [ 'Image', 'Smiley' ] },
            '/',
            { name: 'styles', items: [ 'Styles', 'Format', 'Font', 'FontSize' ] },
            { name: 'tools', items: [ 'Maximize', 'ShowBlocks' ] },
        ],
        height: '25rem',
        resize_minHeight: '5rem',
        image_previewText :" ",
        upload_hidden:false,
        removeDialogTabs:'image:advanced;image:Link',
        filebrowserImageUploadUrl:"/api/v1/image/upload",
        filebrowserUploadUrl:"/api/v1/image/upload",
        //enterMode:CKEDITOR.ENTER_BR, //屏蔽换行符<br>
        //shiftEnterMode:CKEDITOR.ENTER_P, //屏蔽段落<p>
        extraPlugins:'uploadimage',
        // extraPlugins:['codesnippet','uploadimage'],
        codeSnippet_theme: 'zenburn'
    });

    var qrform = $("#advance_reply_form")
    var jsubmit = $('#postsubmit');
    var attachUploader = $("#add_attach");
    var jattachparent = $('.attachlist_parent');
    var maxSize = 1*1024*1024

    qrform.on("keydown", function () {
        if(event.keyCode==13) {
            return false;
        }
    })

    jsubmit.on('click', function() {
        if (CKEDITOR.instances.editor1.getData().length == 0) {
            $.alert("亲，写点什么再提交吧 ^_^")
            return;
        }

        qrform.reset();
        jsubmit.button('loading');
        var postdata = qrform.serializeObject();
        postdata.message = CKEDITOR.instances.editor1.getData();
        console.log(postdata)

        $.xpost(qrform.attr('action'), postdata, function(code, message) {
            console.log(code, ":", message)
            if(code == 200) {
                $.alert("修改成功")
                setTimeout(function () {
                    // addNewPostElement()
                    history.back()
                }, 2000)
            } else if(code < 0) {
                $.alert(message);
                jsubmit.button('reset');
            } else {
                jform.find('[name="'+code+'"]').alert(message).focus();
                jsubmit.button('reset');
            }
        });

        return false;
    });

    function afterAddNewThread() {
        var jsubmit = $('#postsubmit')
        jsubmit.button('reset');
    }

    function trimChar(str, char, type) {
        if (char) {
            if (type == 'left') {
                return str.replace(new RegExp('^\\'+char+'+', 'g'), '');
            } else if (type == 'right') {
                return str.replace(new RegExp('\\'+char+'+$', 'g'), '');
            }
            return str.replace(new RegExp('^\\'+char+'+|\\'+char+'+$', 'g'), '');
        }
        return str.replace(/^\s+|\s+$/g, '');
    }

    attachUploader.on('change', function (e) {
        sessionStorage.setItem("test", 1)
        var fd = new FormData()
        attachfile = attachUploader[0].files[0]
        console.log(attachfile)

        var filesSize = attachfile.size
        // 禁止上传大于1m的文件
        console.log(attachfile.size)
        if (filesSize > maxSize) {
            $.alert("文件大于1M，不能上传")
            return
        }

        fd.append("upload", attachfile)
        {{/*fd.append("thread_id", {{.post.ThreadID}})*/}}
        fd.append("post_id", {{.post.ID}})
        $.ajax({
            url: "/api/v1/attach/add",
            data: fd,
            type: "POST",
            contentType: false,
            processData:false,
            success: function(res) {
                //成功
                console.log(res)
                // return
                if (res.code == 200) {
                    // 并发下会 服务端 session 写入会有问题，由客户端控制改为串行
                    if (!jattachparent.find('.attachlist').length) {
                        jattachparent.append('<fieldset class="fieldset"><legend>上传的附件</legend><ul class="attachlist"><ul></fieldset>');
                    }
                    // 添加福建区域
                    message = res.data
                    addAttachLi(message.url, message.filetype, 1, message.orgfilename)

                    $.alert("上传成功")
                    /*setTimeout(function(){
                        location.reload()
                    }, 2000)*/
                } else {
                    $.alert(res.message)
                    return
                }
            }
        })
    });

    function addAttachLi(url, filetype, aid, orgfilename) {
        $('.attachlist').append('<li aid="' + aid + '"><a class="attachfile" orgfilename="' + orgfilename + '"  href="' + message.url + '" target="_blank"><i class="icon filetype ' + filetype + '"></i> ' + orgfilename + '</a> <a href="javascript:void(0);" class="delete ml-2"><i class="icon-remove"></i> 删除</a></li>');
    }

    function deleteAttach(elem, postId, attachId) {
        var fd = new FormData()
        fd.append("post_id", postId)
        fd.append("attach_id", attachId)
        $.ajax({
            url: "/api/v1/attach/delete",
            data: fd,
            type: "POST",
            contentType: false,
            processData:false,
            success: function(res) {
                //成功
                console.log(res)
                // return
                if (res.code == 200) {
                    if ($('.attachlist').find("li").length == 1) {
                        $('.fieldset').remove()
                    } else {
                        $(elem).parent().remove()
                    }
                } else {
                    $.alert(res.message)
                    return
                }
            }
        })
    }

</script>
{{ template "layout/footer" .}}